package com.old.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    private static final String KEY = "yixue";
//    private static final long EXPIRATION_MS =  60 * 100; //  10秒钟
    private static final long EXPIRATION_MS = 30 * 60 * 1000; // 30 分钟（毫秒）


    //	接收业务数据,生成token并返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_MS))
                .sign(Algorithm.HMAC256(KEY));
    }

	//接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

    //接收token解析userid
    public static Integer getUserIdFromToken(String token) {

        if (token == null || token.trim().isEmpty()) {
            throw new IllegalArgumentException("token为空");
        }

        try {
            Map<String,Object> userInfo =  parseToken(token);
            return (Integer) userInfo.get("id");
        } catch (JWTVerificationException e) {
            // Token 校验失败
            throw new SecurityException("Invalid token", e);
        } catch (NumberFormatException e) {
            // userId 转换失败
            throw new NumberFormatException("Invalid user ID format in token");
        }
    }

    //接收token解析avatar
    public static String getAvatarFromToken(String token) {

        if (token == null || token.trim().isEmpty()) {
            throw new IllegalArgumentException("token为空");
        }

        try {
            Map<String,Object> userInfo =  parseToken(token);
            return (String) userInfo.get("avatar");
        } catch (JWTVerificationException e) {
            // Token 校验失败
            throw new SecurityException("Invalid token", e);
        } catch (NumberFormatException e) {
            // userId 转换失败
            throw new NumberFormatException("Invalid user avatar format in token");
        }
    }

    //接收token解析username
    public static String getUserNameFromToken(String token) {

        if (token == null || token.trim().isEmpty()) {
            throw new IllegalArgumentException("token为空");
        }

        try {
            Map<String,Object> userInfo =  parseToken(token);
            return (String) userInfo.get("username");
        } catch (JWTVerificationException e) {
            // Token 校验失败
            throw new SecurityException("Invalid token", e);
        } catch (NumberFormatException e) {
            // userId 转换失败
            throw new NumberFormatException("Invalid user username format in token");
        }
    }
}
